//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 美食家 on 17/4/9.
//  Copyright © 2017年 不孤独的美食家. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    var webView : UIWebView = UIWebView()

    override func loadView() {
        view=webView
        webView.scrollView.isScrollEnabled=false
        webView.delegate=self
        view.backgroundColor=UIColor.white
        title="登陆新浪微博"
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        guard let url = URL(string:urlString) else {
            return
        }
//        print("\(urlString)")
        
        let request=URLRequest(url: url)
        
        webView.loadRequest(request)
    }
    
    /// MARK - 关闭控制器
    @objc func close() -> Void {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc func autoFill() -> Void{
        /** 在这里将你微博的账号密码换成你的就好了 */
        let js = "document.getElementById('userId').value = '15575385930';"+"document.getElementById('passwd').value = '';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    
    }
}

extension OAuthViewController : UIWebViewDelegate{

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
        
              return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false{
        
            close()
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        /**授权码： bd19ecba9bea813e5495c9ce93c39cd6*/
        print("授权码：\(code)")
        LHNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登陆成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil, userInfo: nil)
                self.close()
            }
        }
        return false
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.showInfo(withStatus: "正在加载")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
}
